import Vue from 'vue'
import Router from 'vue-router'
import routes from './routers'
import store from '@/store'
import iView from 'iview'
import { canTurnTo, setTitle, setToken } from '@/libs/util'

Vue.use(Router)
const router = new Router({
  routes,
  mode: 'hash'
})

const turnTo = (to, rights, next) => {
  if (canTurnTo(to.name, rights, routes)) next() // 有权限，可访问
  else next({ replace: true, name: 'error_401' }) // 无权限，重定向到401页面
}

router.beforeEach((to, from, next) => {
  iView.LoadingBar.start()
  //如果是首页，则接受传过来的token
  if(from.path=="/" && to.path=='/home'){
    let token = to.query.token;
    //保存该token
    setToken(token)
    //获取用户信息
    store.dispatch('getUserInfo')
    //获取用户权限列表
    store.dispatch('getRights')
  }
  //校验用户权限
  turnTo(to, store.state.user.rights, next)
})

router.afterEach(to => {
  setTitle(to, router.app)
  iView.LoadingBar.finish()
  window.scrollTo(0, 0)
})

export default router
